<?php
class M_Links
{
  private $common_names = array(
				"长子","次子","三子","四子","五子","六子","七子","八子","九子","十子","十一子","十二子","十三子","十四子","十五子","十六子","十七子","十八子","十九子","二十子",
			  	"长女","次女","三女","四女","五女","六女","七女","八女","九女","十女","十一女","十二女","十三女","十四女","十五女","十六女","十七女","十八女","十九女","二十女",
			  	".*氏"
				);
  /*
   * get latest names and links list
   * names和links一一对应
   * example: names: 毛泽东 李云龙
   * links:<a>毛泽东</a>(家谱，主页，相册)   <a>李云龙</a>(家谱，主页，相册) 
   * @return list($names, $links) 
   **/
  public function get_name_links_array()
  {
    $db = new M_qin_users();
    $res = $db->get_users(array("state='".RESOURCE_STATE_INIT."'"));
    $users = M_Tools::convert_mysql_results_to_array($res, 'id', 'realname');
    $links = array();
    $names = array();
    $i = 0;
    $common_exp = "/".implode('|', $this->common_names)."/";
    foreach($users as $id=>$name)
      {
	/* 跳过通用的名字，如长子、三女、刘氏 等无意义的名字，*/
	if (preg_match($common_exp, $name))
	  continue;

	$names[$i] = $name;
	$links[$i] = "<a href='/tree/index?userid=${id}'>${name}</a>（<a href='/tree/index?userid=${id}'>家谱</a>,<a href='/users/home?userid=${id}'>主页</a>,<a href='/users/album?userid=${id}'>相册</a>）";
	$i++;
      }
    return array($names, $links);
  }

  /** 
   * @params $event string(event) which you want to replace name to <a href=''>name</a>(家谱，主页，相册)
   * @params $name the event's owner, who don't need to replace in the event
   * @return replaced event
   * */
  public function add_links($event, $name)
  {
    list($names, $links) = $this->get_name_links_array();

    $length = 30;
    $offset = 0;

    $matched = array();
    /* 
     * expression can't be very long, so slice it and preg them, 
     * then combine the $matches in $matched
     * */
    while($offset< count($names))
      {
	$n = array_slice($names, $offset, $length);
	$offset += $length;
	$exp = "/".implode('|', $n)."/";
	$ret = preg_match_all($exp, $event, $matches);
	if ($ret)//$matches[0])
	  {
	    foreach($matches as $m)
	      if ($m[0] && $name != $m[0])
		$matched[] = $m[0];
	  }
      }
    $replace = array();
    $expr = array();
    /* 
     * $expr           $replace
     * /(?<!\>)毛泽东/  <a href=''>毛泽东</a>(家谱，主页，相册)
     * /(?<!\>)梁启超/  <a href=''>梁启超</a>(家谱，主页，相册)
     * */
    foreach($matched as $k => $m)
      {
	$key = array_search($m, $names);
	//名字的前面不是‘>’（即不是连接<a href=''>xxx</a>）
	$expr[$k] = "/(?<!\>)$m/"; 
	$replace[$k] = $links[$key];
      }
    $str = preg_replace($expr, $replace, $event);
    return $str;
  }

}
